//
//  TTBeiLvSetViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/8.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTBeiLvSetViewController.h"
#import "TTBeiLvViewCell.h"

static NSString *cellID = @"cell";

@interface TTBeiLvSetViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) TTDianpuManagerModel *managerModel;

@end

@implementation TTBeiLvSetViewController

- (instancetype)initWithManagerModel:(TTDianpuManagerModel *)managerModel
{
    self = [super init];
    if (self) {
        self.managerModel = managerModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"倍率设置";
    
    UIButton *saveBtn = [UIButton createButtonWithTitle:@"保存" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:15] backgroundColor:nil target:self action:@selector(saveAction)];
    saveBtn.frame = CGRectMake(0, 0, 50, 44);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    
    [self setupdatas];
}


//- (void)backAction
//{
//    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"如不保存，填写的信息将会丢失" cancelTitle:@"取消" cancelBlock:^{
//        [self.navigationController popViewControllerAnimated:YES];
//    } confirmTitle:@"保存" confirmBlock:^BOOL{
//        [self saveAction];
//        return YES;
//    }];
//    [TYShowAlertView showAlertViewWithView:alertView backgoundTapDismissEnable:YES];
//}

// 设置上传参数
- (NSMutableArray *)setUploadParamsWithArray:(NSArray *)array
{
    NSMutableArray *uploadArray = [NSMutableArray array];
    for (TTBeiLvModel *model in array) {
        if (model.field.length == 0) {
            continue;
        }
        if (model.content.length == 0) {
            [self.view makeToast:[NSString stringWithFormat:@"请输入%@ 的倍率", model.title]];
            return nil;
        } else {
            // 获取 数字
            NSString *suffixStr = [model.title componentsSeparatedByString:@" "].lastObject;
            if ([suffixStr hasSuffix:@"ct"]) {
                suffixStr = [suffixStr substringToIndex:suffixStr.length - 2];
            }
            NSArray *countArray;
            if ([suffixStr containsString:@"~"]) {
                countArray = [suffixStr componentsSeparatedByString:@"~"];
            } else {
                NSString *oneStr = [suffixStr substringFromIndex:1];
                countArray = @[oneStr, @"999999999"];
            }
            NSString *twoStr = countArray.lastObject;
            if ([twoStr containsString:@"."]) {
                twoStr = [NSString stringWithFormat:@"%.1f", twoStr.floatValue];
            }
            NSDictionary *dic = @{
                @"MinMum" : countArray.firstObject,
                @"MaxMum" : twoStr,
                @"Rate" : model.content
            };
            [uploadArray addObject:dic];
        }
    }
    
    return uploadArray;
}

// 保存设置
- (void)saveAction
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    // 1、空托
    for (TTBeiLvModel *model in self.dataArray.firstObject) {
        if (model.content.length == 0) {
            [self.view makeToast:[NSString stringWithFormat:@"请输入%@", model.title]];
            return;
        } else {
            [dic setObject:model.content forKey:model.field];
        }
    }
    // 2、成品
    NSMutableArray *finishArray = [self setUploadParamsWithArray:self.dataArray[1]];
    // 3、空托
    NSMutableArray *luoshiArray = [self setUploadParamsWithArray:self.dataArray.lastObject];
    if (finishArray == nil || luoshiArray == nil) {
        return;
    }
    [dic setObject:finishArray forKey:@"ShopFinishedRateList"];
    [dic setObject:luoshiArray forKey:@"ShopDiamondsRateList"];
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:setShopRate_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreashDatas" object:nil];
        [self.navigationController.view makeToast:@"设置成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *array = self.dataArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = self.dataArray[indexPath.section];
    TTBeiLvViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = array[indexPath.row];
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == self.dataArray.count - 1) {
        return 0;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == self.dataArray.count - 1) {
        return [UIView new];
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 10)];
    view.backgroundColor = UIColorHex(F1F5F6);
    return view;

}

- (void)setupdatas
{
    [self.dataArray removeAllObjects];
    NSMutableArray *array1 = [NSMutableArray array];
    [array1 addObject:[TTBeiLvModel setModelWithTitle:@"空托倍率" content:self.managerModel.ShopRate field:@"ShopRate"]];
    
    NSMutableArray *array2 = [NSMutableArray array];
    [array2 addObject:[TTBeiLvModel setModelWithTitle:@"成品倍率" content:@"" hiddenTF:YES]];
    for (TTShopFinishedRateModel *model in self.managerModel.ShopFinishedRate) {
        NSString *title = [NSString stringWithFormat:@"成本价 %@~%@", model.MinMum, model.MaxMum];
        TTBeiLvModel *blmodel = [TTBeiLvModel setModelWithTitle:title content:model.Rate field:@"ShopFinishedRateList"];
        [array2 addObject:blmodel];
    }
    TTBeiLvModel *lastBLmodel = array2.lastObject;
    TTShopFinishedRateModel *model = self.managerModel.ShopFinishedRate.lastObject;
    lastBLmodel.title = [NSString stringWithFormat:@"成本价 ≥%@", model.MinMum];
    
    NSMutableArray *array3 = [NSMutableArray array];
    [array3 addObject:[TTBeiLvModel setModelWithTitle:@"裸石倍率" content:@"" hiddenTF:YES]];
    [array3 addObject:[TTBeiLvModel setModelWithTitle:@"重量 0~0.49ct" content:self.managerModel.ShopDiamondsRate0 field:@"param.shopDiamondsRate0"]];
    [array3 addObject:[TTBeiLvModel setModelWithTitle:@"重量 0.50~0.69ct" content:self.managerModel.ShopDiamondsRate50 field:@"param.shopDiamondsRate50"]];
    [array3 addObject:[TTBeiLvModel setModelWithTitle:@"重量 0.70~0.99ct" content:self.managerModel.ShopDiamondsRate70 field:@"param.shopDiamondsRate70"]];
    [array3 addObject:[TTBeiLvModel setModelWithTitle:@"重量 1.00~1.99ct" content:self.managerModel.ShopDiamondsRate100 field:@"param.shopDiamondsRate100"]];
    [array3 addObject:[TTBeiLvModel setModelWithTitle:@"重量 ≥2.00ct" content:self.managerModel.ShopDiamondsRate200 field:@"param.shopDiamondsRate200"]];
    
    [self.dataArray addObject:array1];
    [self.dataArray addObject:array2];
    [self.dataArray addObject:array3];
    
    [self setupFooterView];
    
    [self.tableView reloadData];
    
}

- (void)setupFooterView
{
    NSString *str = @"帮助：\n商品出售价格会根据成本价*倍率展示\n示例:成本价1000*倍率1.1=售价1100";
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
    [attr addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13], NSForegroundColorAttributeName : UIColorHex(666666)} range:[str rangeOfString:@"帮助："]];
    [attr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, str.length)];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    UILabel *label = [UILabel labelWithTitle:@"" color:UIColorHex(999999) fontSize:11];
    label.numberOfLines = 0;
    label.attributedText = attr;
    [footerView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(15);
        make.right.equalTo(footerView).mas_offset(-15);
    }];
    
    
    self.tableView.tableFooterView = footerView;
    
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 40;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTBeiLvViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuideBottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


@end
